<template>

  <el-row style="min-height: 300px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" label-width="120px">
      <el-form-item v-show="showOrHideItem.name" label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.code" label="编码" prop="code">
        <el-input v-model="form.code" placeholder="请输入编码" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.parentId" label="父ID" prop="parentId">
        <el-input v-model="form.parentId" placeholder="请输入父ID" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.goodsId" label="产品名称" prop="goodsId">

        <el-select v-model="form.goodsId" filterable placeholder="请输入产品名称" style="width:200px"
                   @change="selectChange">
          <template v-for="item in goodsList">
            <el-option :label="item.name" :value="item.id">
            </el-option>
          </template>
        </el-select>

      </el-form-item>
      <el-form-item v-show="showOrHideItem.goodsCode" label="产品编码" prop="goodsCode">
        <el-input v-model="form.goodsCode" disabled placeholder="请输入产品编码" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.goodsBatch" label="产品批次" prop="goodsBatch">
        <el-input v-model="form.goodsBatch" disabled placeholder="请输入产品批次" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.goodsCategory" label="产品类型" prop="goodsCategory">
        <el-select v-model="form.goodsCategory" disabled filterable placeholder="请输入产品类型" style="width:200px">
          <el-option
            v-for="item in goodsCategoryList"
            :key="item.code"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.spec" label="产品规格" prop="spec">
        <el-input v-model="form.spec" disabled placeholder="请输入产品规格" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.barcode" label="条码" prop="barcode">
        <el-input v-model="form.barcode" disabled placeholder="请输入条码" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.prePurchasePrice" label="预设采购成本" prop="prePurchasePrice">
        <el-input v-model="form.prePurchasePrice" disabled placeholder="请输入预设采购成本" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.unit" label="计量单位" prop="unit">
        <el-select v-model="form.unit" disabled placeholder="请选择计量单位" style="width:200px">
          <el-option
            v-for="dict in dict.type.mes_measurement_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.bomQty" label="数量" prop="bomQty">
        <el-input v-model="form.bomQty"
                  placeholder="请输入数量"
                  style="width:200px" type="number"/>
      </el-form-item>
      <!--      <el-form-item v-show="showOrHideItem.deleteFlag" label="删除标识" prop="deleteFlag">-->
      <!--        <el-input v-model="form.deleteFlag" placeholder="请输入删除标识" style="width:200px"/>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item v-show="showOrHideItem.createUserId" label="创建者ID" prop="createUserId">-->
      <!--        <el-input v-model="form.createUserId" placeholder="请输入创建者ID" style="width:200px"/>-->
      <!--      </el-form-item>-->
      <!--      <el-form-item v-show="showOrHideItem.updateUserId" label="更新者ID" prop="updateUserId">-->
      <!--        <el-input v-model="form.updateUserId" placeholder="请输入更新者ID" style="width:200px"/>-->
      <!--      </el-form-item>-->
      <el-form-item v-show="showOrHideItem.total_cost" label="合计成本" prop="totalCost">
        <el-input v-model="form.totalCost"
                  placeholder="请输入合计成本"
                  style="width:200px" type="number"/>

      </el-form-item>
      <el-form-item v-show="showOrHideItem.req_time" label="需求时间" prop="reqTime">
        <el-date-picker v-model="form.reqTime"
                        clearable
                        placeholder="请选择需求时间"
                        style="width:200px"
                        type="date"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>

      <el-form-item v-show="showOrHideItem.is_picked" label="是否领料" prop="isPicked">
        <el-input v-model="form.isPicked" placeholder="请输入是否领料" style="width:200px"/>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.start_time" label="开始时间" prop="startTime">
        <el-date-picker v-model="form.startTime"
                        clearable
                        placeholder="请选择开始时间"
                        style="width:200px"
                        type="date"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item v-show="showOrHideItem.end_time" label="结束时间" prop="endTime">
        <el-date-picker v-model="form.endTime"
                        clearable
                        placeholder="请选择结束时间"
                        style="width:200px"
                        type="date"
                        value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>


    </el-form>


    <el-row justify="end" type="flex">
      <el-button v-show=" showOrHideItem.submit" type="primary" @click="submit">提交</el-button>
    </el-row>
  </el-row>

</template>

<script>


import {goodsListAll} from "../../../../api/basic/goods";
import {addBom, updateBom} from "../../../../api/basic/bom";
import {deepClone} from "../../../../utils";
import {goodsCtgListAll} from "../../../../api/basic/goodsctg";
import {addProjectBom, updateProjectBom} from "@/api/prdmgt/projectBom";

const resetForm = () => {
  return {
    id: null,
    name: null,
    code: null,
    parentId: null,
    goodsId: null,
    goodsName: null,
    goodsCode: null,
    goodsBatch: null,
    goodsCategory: null,
    spec: null,
    barcode: null,
    prePurchasePrice: null,
    unit: null,
    bomQty: null,
    totalCost: null,
    reqTime: null,
    isPicked: null,
    startTime: null,
    endTime: null,
    // deleteFlag: null,
    // createUserId: null,
    // createBy: null,
    // createTime: null,
    // updateUserId: null,
    // updateBy: null,
    // updateTime: null,
  }
}
const showOrHide = () => {
  return {
    id: true,
    name: false,
    code: false,
    parentId: false,
    goodsId: false,
    goodsName: false,
    goodsCode: false,
    goodsBatch: false,
    goodsCategory: false,
    spec: false,
    barcode: false,
    prePurchasePrice: false,
    unit: false,
    bomQty: false,
    deleteFlag: false,
    bom_qty: false,
    total_cost: false,
    req_time: false,
    is_picked: false,
    start_time: false,
    end_time: false,
    createUserId: false,
    createBy: false,
    createTime: false,
    updateUserId: false,
    updateBy: false,
    updateTime: false,
    submit: false,
  }
}
export default {
  name: "Form",
  dicts: ['mes_measurement_unit'],
  data() {
    return {
      goodsCategoryList: [],
      goodsList: [],
      rules: {
        goodsId: [
          {required: true, message: "产品名称不能为空", trigger: "blur"}
        ],
      },
    }
  },
  props: {
    showObj: {
      type: Object,
      default() {
        return {}
      }
    },
    oldFormData: {
      type: Object,
      default() {
        return {};
      }
    },
    formData: {
      type: Object,
      default() {
        return resetForm();
      }
    },
    isFromProject: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    form: {
      handler(newVal, oldVal) {
        this.$emit('formChange',  this.findObjOperate(newVal , this.oldFormData).length > 0)
      },
      deep: true
    }
  },
  computed: {
    form: {
      set(obj) {
        this.$emit('update:formData', obj)
      },
      get() {
        return this.formData
      }
    },
    showOrHideItem() {
      let obj = {
        ...showOrHide(),
        ...this.showObj
      }
      return obj
    }
  },
  created() {
    this.goodsListAllFn()
    this.getGoodsCategoryList()
  },
  methods: {

    findObjOperate(obj1, obj2) {
      const result = [];
      //遍历obj1的键数组，因为obj1和obj2结构相同，所以不考虑结构上的差异
      Array.from(new Set(Object.keys(obj1).concat(Object.keys(obj2)))).forEach(key => {
        if (obj1[key] !== obj2[key] && key != 'status' && key != 'params' && key !='children') {
          //将变化过的属性挂载到返回对象中
          result.push(key);
        }
      });
      return result;
    },
    async getGoodsCategoryList() {
      await goodsCtgListAll().then(res => {
        this.goodsCategoryList = res.data
      })
    },
    selectChange(value) {
      let item = this.goodsList.find(d => d.id == value)
      this.form.goodsId = item.id && item.id || ''
      this.form.goodsName = item.name && item.name || ''
      this.form.goodsCode = item.code && item.code || ''
      this.form.goodsBatch = item.goodsBatch && item.goodsBatch || ''
      this.form.goodsCategory = item.goodsCategory && item.goodsCategory || ''
      this.form.spec = item.spec && item.spec || ''
      this.form.barcode = item.barcode && item.barcode || ''
      this.form.prePurchasePrice = item.prePurchasePrice && item.prePurchasePrice || ''
      this.form.unit = item.unit && item.unit || ''
      this.form.totalCost = item.totalCost && item.totalCost || ''
      this.form.reqTime = item.reqTime && item.reqTime || ''
      this.form.isPicked = item.isPicked && item.isPicked || ''
      this.form.startTime = item.startTime && item.startTime || ''
      this.form.endTime = item.endTime && item.endTime || ''
    },
    submit(callback) {
      if (this.form.status === 'add') {
        if (this.isFromProject) {
          addProjectBom(this.form).then(res => {
            this.form = deepClone(res.data)
            this.$message.success(res.msg)
            this.$emit('onSubmit')
            this.$emit('formChange', false)
            if(typeof callback === 'function'){
              callback()
            }
          })
        } else {
          addBom(this.form).then(res => {
            this.form = deepClone(res.data)
            this.$message.success(res.msg)
            this.$emit('onSubmit')
          })
        }
      } else {
        if (this.isFromProject) {
          updateProjectBom(this.form).then(res => {
            this.$message.success(res.msg)
            this.$emit('onSubmit')
            this.$emit('formChange', false)
            if(typeof callback === 'function'){
              callback()
            }
          })
        } else {
          updateBom(this.form).then(res => {
            this.$message.success(res.msg)
            this.$emit('onSubmit')
          })
        }
      }
    },
    async goodsListAllFn() {
      await goodsListAll().then(response => {
        this.goodsList = response.data;

      })
    },
  }
}
</script>

<style>
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none;
}

input[type="number"] {
  -moz-appearance: textfield;
}
</style>
